<?php

namespace app\pay\controller;

use app\pay\logic\PayCallback;
use app\pay\service\WxPayService;
use think\facade\Log;

class WxPay extends Base
{
    /**
     * notify
     */
    public function notify(): string
    {
        // 记录请求日志
        Log::info('支付回调参数', $_POST);

        // 获取参数
        $data = $_POST;
        $appId = $this->request->param('appId', '');
        if (!$appId) {
            return '请求租户编号为空';
        }
        if (!$data) {
            return '请求数据不得为空';
        }

        // 提取参数
        $code = $data["code"] ?? '';
        $orderNo = $data["orderNo"] ?? '';
        $outTradeNo = $data["outTradeNo"] ?? '';
        $payNo = $data["payNo"] ?? '';
        $money = $data["money"] ?? '';
        $mchId = $data["mchId"] ?? '';

        // 提取签名
        $sign = $data['sign'] ?? '';
        if (!$sign) {
            return '未获取到签名字符串';
        }

        // 签名验证
        $signData = [];
        $signData["code"] = $code;
        $signData["orderNo"] = $orderNo;
        $signData["outTradeNo"] = $outTradeNo;
        $signData["payNo"] = $payNo;
        $signData["money"] = $money;
        $signData["mchId"] = $mchId;
        $signIsPass = (new WxPayService())->setAppId($appId)->checkSign($sign, $signData);
        if (!$signIsPass) {
            return '签名不正确';
        }

        // 订单处理
        if (!$outTradeNo) {
            return '未获取到订单号';
        }

        // 订单处理
        try {
            (new PayCallback())->invoke($outTradeNo, $orderNo);
        } catch (\Exception $exception) {
            return $exception->getMessage();
        }

        // 返回
        return 'SUCCESS';
    }
}
